package com.koron.tool.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.DefaultIdGenerator;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.common.core.business.workflow.bean.properties.WorkflowProperties;
import com.koron.common.core.business.workflow.templates.WorkFlowHandler;
import com.koron.tool.bean.*;
import com.koron.tool.enums.WarningReasonEnum;
import com.koron.tool.fegin.ExcelFeginService;
import com.koron.tool.fegin.SystemFeignService;
import com.koron.tool.listener.excel.ImportToolDataListener;
import com.koron.tool.mapper.DictDataMapper;
import com.koron.tool.mapper.ToolAccountsManagerMapper;
import com.koron.tool.mapper.ToolScrapDataMapper;
import com.koron.tool.mapper.ToolWarningInfoMapper;
import com.koron.tool.service.ToolScrapDataService;
import com.koron.tool.util.BeanUtil;
import com.koron.tool.util.PdfUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Slf4j
public class ToolScrapServiceImpl implements ToolScrapDataService {

    @Autowired
    private WorkFlowHandler workFlowHandler;

    @Autowired
    private ExcelFeginService excelFeginService;

    @Autowired
    private SystemFeignService systemFeignService;

    /**
     * 预报废工具单查询
     *
     * @param factory
     * @param query
     * @return
     */
    @Override
    @TaskAnnotation("getYuScrapList")
    public Response getYuScrapList(SessionFactory factory, ToolQuery query) {
        try {
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            PageHelper.startPage(query.getPage(), query.getPageSize());
            List<ToolBean> list = mapper.getYuScrapList(query);
            ToolAccountsManagerMapper toolMapper = factory.getMapper(ToolAccountsManagerMapper.class);
            list.forEach(bean->{
                //所属类型
                ToolGroupBean getToolGroupByCode = toolMapper.getToolGroupByCode(bean.getToolTyleCode());
                if (null != getToolGroupByCode) {
                    bean.setToolTyle(getToolGroupByCode.getName());
                }
                if (StringUtils.isEmpty(bean.getScrapWhy())){
                    bean.setScrapWhy("due");
                }
            });
            PageInfo pageInfo = new PageInfo(list);
            return Response.succ(pageInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }
    }

    /**
     * 移除预报废工具中手动报废的工具
     *
     * @param factory
     * @param id
     * @return
     */
    @Override
    @TaskAnnotation("deleteYuScrap")
    public Response deleteYuScrap(SessionFactory factory, String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return Response.fail("参数id不能为空");
            }
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            Integer delete = mapper.deleteYuScrap(id);
            return Response.ok(delete);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("移除失败");
        }
    }

    /**
     * 查看报废单列表
     *
     * @param factory
     * @param query
     * @return
     */
    @Override
    @TaskAnnotation("getScrapList")
    public Response getScrapList(SessionFactory factory, ScrapQuery query) {
        try {
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            PageHelper.startPage(query.getPage(), query.getPageSize());
            List<ScrapListBean> list = mapper.getScrapList(query);
            PageInfo pageInfo = new PageInfo(list);
            return Response.succ(pageInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }
    }

    /**
     * 生成报废单
     *
     * @param factory
     * @param user
     * @param query
     * @return
     */
    @Override
    @TaskAnnotation("addScrapList")
    public Response addScrapList(SessionFactory factory, EamUser user, ScrapListBean query, Integer operation) {
        try {
            if (StringUtils.isEmpty(query.getTitle())) {
                return Response.fail("标题不能为空");
            }
            if (StringUtils.isEmpty(query.getBelongsUnitId())) {
                return Response.fail("请选择工器具管理单位");
            }
            if (StringUtils.isEmpty(query.getApplicanter())) {
                return Response.fail("请选择制单人");
            }

            String orderNo = DefaultIdGenerator.getInstance().generateLongId();
            query.setOrderNo(orderNo);
            query.setGenerateDate(System.currentTimeMillis() / 1000L);
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            BeanUtil.add(user, query);
            //当前节点人
            query.setCurrenter(user.getName());
            if (operation == 0) {
                query.setAuditStatus("draft");
            } else {
                query.setAuditStatus("review");
            }
            Integer value = mapper.addScrapList(query);

            //报废单明细
            List<ScrapDetailBean> detList = query.getDetList();
            if (detList != null) {
                for (ScrapDetailBean bean : detList) {
                    if (StringUtils.isEmpty(bean.getCode())) {
                        return Response.fail("工具编码不能为空");
                    }
                    if (StringUtils.isEmpty(bean.getName())) {
                        return Response.fail("工具名称不能为空");
                    }
                    if (StringUtils.isEmpty(bean.getToolTyleCode())) {
                        return Response.fail("工具类型不能为空");
                    } else {
                        bean.setToolTyle(bean.getToolTyleCode());
                    }
                    if (StringUtils.isEmpty(bean.getInventoryStatus())) {
                        return Response.fail("库存状态不能为空");
                    }
                    if (StringUtils.isEmpty(bean.getWarehouseId())) {
                        return Response.fail("所属库房ID不能为空");
                    }
                    if (StringUtils.isEmpty(bean.getWarehouse())) {
                        return Response.fail("所属库房不能为空");
                    }
                    if (StringUtils.isEmpty(bean.getBelongsUnitName())) {
                        return Response.fail("所属单位不能为空");
                    } else {
                        bean.setBelongsUnit(bean.getBelongsUnitName());
                    }
                    bean.setBelongsUnitId(query.getBelongsUnitId());
                    bean.setScrapId(query.getId());
                    BeanUtil.add(user, bean);
                    value = mapper.addScrapInfo(bean);
                }
                // 生成报废单后取消预警
                Set<String> codes = new HashSet<>();
                detList.forEach(detailBean -> {
                    codes.add(detailBean.getCode());
                });
                factory.getMapper(ToolWarningInfoMapper.class)
                        .batchUpdateStatus(WarningReasonEnum.REACH_THE_SCRAP_PERIOD.getReason(), codes);
            }

            if (value > 0 && operation == 1) {
                // TODO 启动流程
                //启动工作流 执行工作流平台指定的审批流程
                WorkflowProperties wfp = WorkflowProperties.init("tool_sracp_code");
                Map map = new HashMap(5);
                //指定下一个节点人
                map.put("auditer", query.getAuditer());
                //启动工作流
                workFlowHandler.start(wfp, query.getId(), query.getOrderNo(), query.getTitle(), map);
                query.setCurrentNode("Process-task1");
                query.setCurrenter(query.getAuditerName());

                //修改单据信息
                mapper.updateScrapList(query);
            }

            return Response.ok(value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("执行失败");
        }
    }

    /**
     * 草稿状态修改报废单
     *
     * @param factory
     * @param user
     * @param bean
     * @param operation
     * @return
     */
    @Override
    @TaskAnnotation("updateScrapList")
    public Response updateScrapList(SessionFactory factory, EamUser user, ScrapListBean bean, Integer operation) {
        try {
            if (StringUtils.isEmpty(bean.getTitle())) {
                return Response.fail("标题不能为空");
            }
            if (StringUtils.isEmpty(bean.getBelongsUnitId())) {
                return Response.fail("请选择工器具管理单位");
            }
            if (StringUtils.isEmpty(bean.getApplicanter())) {
                return Response.fail("请选择制单人");
            }
            //单号不能修改
            //String orderNo = DefaultIdGenerator.getInstance().generateLongId();
            //bean.setOrderNo(orderNo);
            bean.setGenerateDate(System.currentTimeMillis() / 1000L);
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            BeanUtil.update(user, bean);
            if (operation == 0) {
                bean.setAuditStatus("draft");
            } else {
                bean.setAuditStatus("review");
            }
            Integer value = mapper.updateScrapList(bean);

            if (value > 0 && operation == 1) {
                // TODO 启动流程
                //启动工作流 执行工作流平台指定的审批流程
                WorkflowProperties wfp = WorkflowProperties.init("tool_sracp_code");
                Map map = new HashMap(5);
                //指定下一个节点人
                map.put("auditer", bean.getAuditer());
                //启动工作流
                workFlowHandler.start(wfp, bean.getId(), bean.getOrderNo(), bean.getTitle(), map);
                bean.setCurrentNode("Process-task1");
                bean.setCurrenter(bean.getAuditerName());

                mapper.updateScrapList(bean);
            }

            return Response.ok(value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("执行失败");
        }
    }

    /**
     * 流程审批回调
     *
     * @param factory
     * @param redirectQuery
     * @return
     */
    @Override
    @TaskAnnotation("updateStateScrap")
    public Response updateStateScrap(SessionFactory factory, RedirectQuery redirectQuery) {
        try {
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            ToolAccountsManagerMapper tmapper = factory.getMapper(ToolAccountsManagerMapper.class);
            //获取业务id
            String dataId = redirectQuery.getDataId();
            //根据业务ID获取获取当前单据
            ScrapListBean scrapInfo = mapper.scrapInfo(dataId);

            //修改状态
            if ("END".equals(redirectQuery.getCurNodeCode())) {
                //流程结束，更新状态为归档
                //当前节点名称
                scrapInfo.setCurrentNode(redirectQuery.getCurNodeName());
                //当前处理人
                scrapInfo.setCurrenter(redirectQuery.getRelatedUser());
                //当前审批状态
                scrapInfo.setAuditStatus("archive");

                long nowTimestamp = System.currentTimeMillis() / 1000L;

                // 修改工器具报废时间
                mapper.updateScrapDate(scrapInfo.getId(), nowTimestamp);

                //修改工具状态
                //通过单据ID查单据明细
                List<ScrapDetailBean> ScrapDetailList = mapper.ScrapDetailList(scrapInfo.getId());
                //循环明细，通过code获取工具Id，修改每个工具状态
                for (ScrapDetailBean sbean : ScrapDetailList) {
                    tmapper.updateTooleStatus(sbean.getCode(), nowTimestamp);
                }

            } else if ("CANCEL".equals(redirectQuery.getCurNodeCode())) {
                //流程废弃，更新状态为草稿
                scrapInfo.setCurrentNode("");
                scrapInfo.setCurrenter(redirectQuery.getRelatedUser());
                scrapInfo.setAuditStatus("draft");
            } else if ("Process-task1".equals(redirectQuery.getCurNodeCode())) {
                //流程通过，当前状态为审核中
                scrapInfo.setCurrentNode(redirectQuery.getCurNodeName());
                scrapInfo.setCurrenter(redirectQuery.getRelatedUser());
                scrapInfo.setAuditStatus("review");
            }
            Integer value = mapper.updateScrapList(scrapInfo);


            return Response.ok(value);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail();
        }
    }


    /**
     * 查看报废单详情
     *
     * @param factory
     * @param id
     * @return
     */
    @Override
    @TaskAnnotation("scrapInfo")
    public Response scrapInfo(SessionFactory factory, String id) {
        try {
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            ToolAccountsManagerMapper toolMapper = factory.getMapper(ToolAccountsManagerMapper.class);

            ScrapListBean scrapInfo = mapper.scrapInfo(id);
            //报废单明细列表
            List<ScrapDetailBean> ScrapDetailList = mapper.ScrapDetailList(id);
            for (ScrapDetailBean sbean : ScrapDetailList) {
                //所属类型
                ToolGroupBean getToolGroupByCode = toolMapper.getToolGroupByCode(sbean.getToolTyle());
                if (null != getToolGroupByCode) {
                    sbean.setToolTyle(getToolGroupByCode.getName());
                }
                sbean.setBelongsUnitName(sbean.getBelongsUnit());
                sbean.setToolTyleCode(sbean.getToolTyle());
                ToolGroupBean getToolGroup = toolMapper.getGroup(sbean.getWarehouseId());
                sbean.setWarehouseName(getToolGroup.getName());
            }
            scrapInfo.setDetList(ScrapDetailList);
            return Response.succ(scrapInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("查询失败");
        }
    }

    public String getWarehouseId(SessionFactory factory,String toolTypeId){
        ToolAccountsManagerMapper toolMapper = factory.getMapper(ToolAccountsManagerMapper.class);

        ToolGroupBean getGroupType = null;
        do {
            //根据类型Id查库房
            getGroupType = toolMapper.getGroup(toolTypeId);

        } while (getGroupType.getHierarchy().equals("3"));
        return getGroupType.getId();
    }

    /**
     * 批量导入工具
     *
     * @param factory
     * @param file
     * @param toolTypeId
     * @return
     */
    @Override
    @TaskAnnotation("upload")
    public Response upload(SessionFactory factory, EamUser user, MultipartFile file, String toolTypeId) {
        try {
            ToolAccountsManagerMapper toolMapper = factory.getMapper(ToolAccountsManagerMapper.class);

            EasyExcel.read(file.getInputStream(), new AnalysisEventListener() {

                //每解析一行数据,该方法会被调用一次
                @SneakyThrows
                @Override
                public void invoke(Object demoData, AnalysisContext analysisContext) {
                    // 如果没有指定数据模板, 解析的数据会封装成 LinkedHashMap返回
                    // demoData instanceof LinkedHashMap 返回 true
                    log.info("解析数据为:" + demoData.toString());
                    List keys = new ArrayList();
                    LinkedHashMap<Integer, String> lMap = (LinkedHashMap) demoData;
                    for (Map.Entry<Integer, String> entry : lMap.entrySet()) {
                        log.info(entry.getKey() + " " + entry.getValue());
                        //将excel中的值存入数组
                        keys.add(entry.getValue());
                    }

                    ToolBean bean = new ToolBean();
                    //库存状态
                    bean.setInventoryStatus("in");
                    //可用状态
                    bean.setAvailableStatus("available");
                    //所属库房ID
                    //String getWarehouseId = getWarehouseId(factory,toolTypeId);
                    bean.setWarehouseId(toolTypeId);
                    //所属单位ID
                    ToolGroupBean getGroup = toolMapper.getGroup(toolTypeId);
                    bean.setWarehouse(getGroup.getParent());

                    //用来判断行数
                    String row = keys.get(0).toString();

                    //RFID
                    bean.setRFID(keys.get(1).toString());
                    //工具编码
                    bean.setCode(keys.get(1).toString());
                    //工具名称(必填)
                    bean.setName(keys.get(2).toString());
                    //工具分类
                    bean.setEamType(keys.get(3).toString());
                    //型号
                    if (keys.get(4) != null) {
                        bean.setModel(keys.get(4).toString());
                    }
                    //厂家
                    if (keys.get(5) != null) {
                        bean.setManufacturer(keys.get(5).toString());
                    }
                    //品牌
                    if (keys.get(6) != null) {
                        bean.setBrand(keys.get(6).toString());
                    }
                    //生产日期
                    if (keys.get(7) != null) {
                        bean.setProductionDate(date2TimeStamp(keys.get(7).toString()));
                    }
                    //入库日期
                    if (keys.get(8) != null) {
                        bean.setInStorageDate(date2TimeStamp(keys.get(8).toString()));
                    }
                    //生命周期
                    /*if (keys.get(8) != null) {
                        bean.setLifeCycle(Integer.valueOf(keys.get(8).toString()));
                    }*/
                    //检验周期
                    /*if (keys.get(9) != null) {
                        bean.setInspectionCycle(Integer.valueOf(keys.get(9).toString()));
                    }*/
                    //报废日期(必填)
                    if (keys.get(9) != null) {
                        bean.setScrapDate(date2TimeStamp(keys.get(9).toString()));
                    }
                    //本次检验日期(必填)
                    bean.setNewInspectionDate(date2TimeStamp(keys.get(10).toString()));
                    //下次检验日期(必填)
                    if (keys.get(11) != null) {
                        bean.setNextInspectionDate(date2TimeStamp(keys.get(11).toString()));
                    }
                    //工器具类型编码(默认)
                    bean.setToolTyleCode(keys.get(12).toString());

                    //工具位置
                    if (keys.get(13) != null) {
                        bean.setToolLocation(keys.get(13).toString());
                    }

                    //判重
                    ToolBean getRFID = toolMapper.getRFID(keys.get(1).toString());
                    if (getRFID != null) {
                        //修改数据
                        BeanUtil.update(user, bean);
                        bean.setId(getRFID.getId());
                        toolMapper.updateTool(bean);
                    } else {
                        //插入数据
                        BeanUtil.add(user, bean);
                        toolMapper.insertTool(bean);
                    }
                }

                // 全部解析完成被调用
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    log.info("解析完成...");
                    // 可以将解析的数据保存到数据库
                }
            }).sheet().headRowNumber(1).doRead();

            return Response.success("导入成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("导入失败");
        }
    }

    @Override
    @TaskAnnotation("uploadTest")
    public Response uploadTest(SessionFactory factory, EamUser user, MultipartFile file, String toolTypeId) {
        try {
            ToolAccountsManagerMapper toolMapper = factory.getMapper(ToolAccountsManagerMapper.class);

            //excel数据写入list中
            List<List<ToolBean>> cacheList = new ArrayList<>();
            ImportToolDataListener importToolDataListener = new ImportToolDataListener();
            EasyExcel.read(file.getInputStream(), ToolBean.class, importToolDataListener).sheet().headRowNumber(3).doRead();
            List<ToolBean> toolBeanList = importToolDataListener.getToolBeanList();
            for (ToolBean toolBean : toolBeanList) {
                ToolGroupBean toolTyleNode = toolMapper.getGroupByCode(toolBean.getToolTyleCode());
                if (Objects.isNull(toolTyleNode)) {
                    return Response.fail("不存在编号为[" + toolBean.getToolTyleCode() + "]的分区");
                }
                String warehouseId = toolTyleNode.getParent();
                toolBean.setWarehouseId(warehouseId);
                ToolGroupBean warehouseNode = toolMapper.getGroup(warehouseId);
                toolBean.setWarehouse(warehouseNode.getParent());
            }

            Map<String, String> personInChargeMap = new HashMap<>();
            for (ToolBean toolBean : toolBeanList) {
                String rowl = toolBean.getIdOrder();
                //工具名称非空定位
                if(toolBean.getName()==null){
                    return Response.fail("第"+rowl+"行，第3列，工具名称不能为空 ！");
                }
                //工具分类非空定位
                if(StringUtils.isEmpty(toolBean.getEamType())){
                    return Response.fail("第"+rowl+"行，第4列，工具分类不能为空 ！");
                }
                //生产日期错误定位
                if (StringUtils.isNotEmpty(toolBean.getProductionDateString())) {
                    String productionDateString = toolBean.getProductionDateString();
                    try {
                        toolBean.setProductionDate(date2TimeStamp(productionDateString));
                    } catch (Exception e) {
                        return Response.fail("第" + rowl + "行，第8列，生产日期格式有误 ！");
                    }
                }
                //入库日期错误定位
                if(StringUtils.isNotEmpty(toolBean.getInStorageDateString())){
                    String inStorageDateString = toolBean.getInStorageDateString();
                    try {
                        toolBean.setInStorageDate(date2TimeStamp(inStorageDateString));
                    } catch (Exception e) {
                        return Response.fail("第" + rowl + "行，第9列，入库日期格式有误 ！");
                    }
                }
                //报废日期错误定位
                if(StringUtils.isNotEmpty(toolBean.getScrapDateString())){
                    String scrapDateString = toolBean.getScrapDateString();
                    try {
                        toolBean.setScrapDate(date2TimeStamp(scrapDateString));
                    } catch (Exception e) {
                        return Response.fail("第" + rowl + "行，第10列，报废日期格式有误 ！");
                    }
                }
                //下次检验日期错误定位
                if(StringUtils.isNotEmpty(toolBean.getNewInspectionDateString())){
                    String newInspectionDateString = toolBean.getNewInspectionDateString();
                    try {
                        toolBean.setNewInspectionDate(date2TimeStamp(newInspectionDateString));
                    } catch (Exception e) {
                        return Response.fail("第" + rowl + "行，第12列，本次检验日期格式有误 ！");
                    }
                }
                //下次检验日期错误定位
                if(StringUtils.isNotEmpty(toolBean.getNextInspectionDateString())){
                    String NextInspectionDateString = toolBean.getNextInspectionDateString();
                    try {
                        toolBean.setNextInspectionDate(date2TimeStamp(NextInspectionDateString));
                    } catch (Exception e) {
                        return Response.fail("第" + rowl + "行，第12列，下次检验日期格式有误 ！");
                    }
                }
                // 工具负责人
                String personInCharge = toolBean.getPersonInCharge();
                if (StringUtils.isEmpty(personInCharge)) {
                    return Response.fail("第" + rowl + "行，第15列，工具负责人不能为空！");
                } else {
                    if (personInChargeMap.containsKey(personInCharge)) {
                        toolBean.setPersonInChargeName(personInChargeMap.get(personInCharge));
                    } else {
                        EamUser eamUser = systemFeignService.queryStaffInfo(personInCharge).getData();
                        if (eamUser == null) {
                            return Response.fail("第" + rowl + "行，第15列，工器具负责人[" + personInCharge + "]不存在！");
                        }
                        toolBean.setPersonInChargeName(eamUser.getName());
                        personInChargeMap.put(personInCharge, eamUser.getName());
                    }
                }
            }

            //循环插入数据库
            for(ToolBean toolBean : toolBeanList){
                //判重
                ToolBean getRFID = toolMapper.getRFID(toolBean.getRFID());
                if (getRFID != null) {
                    //修改数据
                    BeanUtil.update(user, toolBean);
                    toolBean.setId(getRFID.getId());
                    toolMapper.updateTool(toolBean);
                } else {
                    //插入数据
                    BeanUtil.add(user, toolBean);
                    toolMapper.insertTool(toolBean);
                }
            }

            return Response.success("导入成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("导入失败");
        }
    }

    @Override
    @TaskAnnotation("exportPdf")
    public void exportPdf(SessionFactory factory, EamUser user, String id, OutputStream os) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            ToolScrapDataMapper mapper = factory.getMapper(ToolScrapDataMapper.class);
            DictDataMapper dmapper = factory.getMapper(DictDataMapper.class);
            ToolAccountsManagerMapper toolMapper = factory.getMapper(ToolAccountsManagerMapper.class);
            // 获取报废单
            ScrapListBean bean = mapper.scrapInfo(id);
            if (null == bean) {
                return;
            }
            // 获取报废单详情
            List<ScrapDetailBean> detailList = mapper.ScrapDetailList(id);
            // 创建Document
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, os);
            writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
            // 设置页面大小
            document.setPageSize(PageSize.A4);
            document.open();
            // 创建一个PDF表单
            PdfPTable table = PdfUtil.createTable(6);
            // 设置字体
            // 标题
            Font headFont = PdfUtil.getFont(14, Font.NORMAL);
            // 表头
            Font tableFont = PdfUtil.getFont(12, Font.NORMAL);
            // 内容
            Font textFont = PdfUtil.getFont(10, Font.NORMAL);
            table.addCell(PdfUtil.createCell("标题", tableFont, Element.ALIGN_LEFT, 1, 0));
            table.addCell(PdfUtil.createCell(bean.getTitle(), tableFont, Element.ALIGN_LEFT, 5, 0));
            table.addCell(PdfUtil.createCell("单据信息", headFont, Element.ALIGN_LEFT, 6, 0));

            table.addCell(PdfUtil.createCell("内容", tableFont, Element.ALIGN_CENTER, 1, 0));
            table.addCell(PdfUtil.createCell(bean.getContent(), textFont, Element.ALIGN_CENTER, 5, 0));
            table.addCell(PdfUtil.createCell("工器具管理单位", tableFont, Element.ALIGN_CENTER, 1, 0));
            table.addCell(PdfUtil.createCell(bean.getBelongsUnit(), textFont, Element.ALIGN_CENTER, 2, 0));
            table.addCell(PdfUtil.createCell("制单人", tableFont, Element.ALIGN_CENTER, 1, 0));
            table.addCell(PdfUtil.createCell(bean.getApplicanter(), textFont, Element.ALIGN_CENTER, 2, 0));
            //table.addCell(PdfUtil.createCell("", tableFont, Element.ALIGN_CENTER, 1, 0));
            //table.addCell(PdfUtil.createCell("", textFont, Element.ALIGN_CENTER, 2, 0));
            table.addCell(PdfUtil.createCell("报废信息", headFont, Element.ALIGN_LEFT, 6, 0));
            table.addCell(PdfUtil.createCell("报废工具清单", tableFont, Element.ALIGN_CENTER, 8, 0));
            table.addCell(PdfUtil.createCell("名称", tableFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(PdfUtil.createCell("所属单位", tableFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(PdfUtil.createCell("工器具类型", tableFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(PdfUtil.createCell("所属库房", tableFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(PdfUtil.createCell("报废日期", tableFont, Element.ALIGN_CENTER, 0, 0));
            table.addCell(PdfUtil.createCell("库存状态", tableFont, Element.ALIGN_CENTER, 0, 0));
            if (null != detailList && detailList.size() > 0) {
                for (ScrapDetailBean detailBean : detailList) {
                    table.addCell(PdfUtil.createCell(detailBean.getName(), textFont, Element.ALIGN_CENTER, 0, 0));
                    table.addCell(PdfUtil.createCell(detailBean.getBelongsUnit(), textFont, Element.ALIGN_CENTER, 0, 0));
                    //所属类型
                    ToolGroupBean getToolGroupByCode = toolMapper.getToolGroupByCode(detailBean.getToolTyle());
                    table.addCell(PdfUtil.createCell(getToolGroupByCode.getName(), textFont, Element.ALIGN_CENTER, 0, 0));
                    //所属库房
                    ToolGroupBean getToolGroup = toolMapper.getGroup(detailBean.getWarehouseId());
                    table.addCell(PdfUtil.createCell(getToolGroup.getName(), textFont, Element.ALIGN_CENTER, 0, 0));
                    table.addCell(PdfUtil.createCell(sdf.format(new Date(detailBean.getScrapDate() * 1000L)), textFont, Element.ALIGN_CENTER, 0, 0));
                    //库存状态
                    List<DictData> getDict = dmapper.getDict("inventoryStatus");
                    for (DictData ddata : getDict) {
                        if (detailBean.getInventoryStatus().equals("in")) {
                            detailBean.setInventoryStatus("在库");

                        } else if (detailBean.getInventoryStatus().equals("out")) {
                            detailBean.setInventoryStatus("借出");
                        }
                    }
                    table.addCell(PdfUtil.createCell(detailBean.getInventoryStatus(), textFont, Element.ALIGN_CENTER, 0, 0));
                }
            }
            document.add(table);
            document.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return;
        }

    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param date_str 字符串日期
     * @return
     */
    /*public static Long date2TimeStamp(String date_str) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            return sdf.parse(date_str).getTime() / 1000;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }*/
    public static Long date2TimeStamp(String date_str) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            return sdf.parse(date_str).getTime() / 1000;
    }


}
